/**
 * PackRegMngAction.java
 * Created at 2017-2-21
 * Created by shihui
 * Copyright (C) 2017 BROADTEXT SOFTWARE, All rights reserved.
 */
package com.broadtext.rms.basic.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.broadtext.common.bean.EntityPageBean;
import com.broadtext.common.exp.ServiceException;
import com.broadtext.rms.basic.model.TmPackSerial;
import com.broadtext.rms.basic.service.IPackRegMngService;
import com.broadtext.rms.basic.service.ITmPackSerialService;
import com.broadtext.rms.monitor.model.TtPack;
import com.github.miemiedev.mybatis.paginator.domain.PageBounds;

/**
 * <p>ClassName: PackRegMngAction</p>
 * <p>Description: 电池注册管理控制层</p>
 * <p>Author: shihui</p>
 * <p>Date: 2017-2-21</p>
 */
@Controller
@RequestMapping("/main/packRegMng")
public class PackRegMngAction {
    /**
     * 日志信息
     */
    public static Logger logger = LoggerFactory.getLogger(TtPack.class);
    
    /**
     * ENABLE 异常；PACK_STATUS:不报废
     */
    private static final String STATUS_ZERO = "0";
    
    /**
     * PACKREG_FLAG:已注册；ENABLE_FLAG:正常；STATUS:电池ID已使用
     */
    private static final String STATUS_ONE = "1";
    
    /**
     * 电池注册管理Service
     */
    @Autowired
    @Qualifier("packRegMngServiceImpl")
    private IPackRegMngService packRegMngService;
    
    /**
     * 电池ID管理Service
     */
    @Autowired
    @Qualifier("tmPackSerialService")
    private ITmPackSerialService packSerialService;
    
    /**
     * 
     * <p>
     * Description: 查询电池注册记录
     * </p>
     * @param request 请求
     * @param response 响应
     */
    @RequestMapping(value = "/findPackRegList.mvc")
    @ResponseBody
    public void findRegionsByType(HttpServletRequest request, HttpServletResponse response) {
        try {
            PageBounds pageBounds;
            pageBounds = new PageBounds();
            Map<String, Object> map;
            String aoData;
            aoData = request.getParameter("aoData");
            JSONArray array;
            array = JSON.parseArray(aoData);
            map = new HashMap<String, Object>();
            if (array != null) {
                Iterator<?> it;
                it = array.iterator();
                while (it.hasNext()) {
                    JSONObject obj;
                    obj = (JSONObject) it.next();
                    if (obj.get("value") != null && !"".equals(obj.get("value") + "")) {
                        map.put(obj.get("name") + "", obj.get("value"));
                    }
                }
            }
            pageBounds.setLimit(Integer.parseInt(map.get("iDisplayLength").toString()));
            pageBounds.setPage(Integer.parseInt(map.get("iDisplayStart").toString()) / pageBounds.getLimit() + 1);
            EntityPageBean<Object> pageBean;
            pageBean = this.packRegMngService.findPackRegList(map, pageBounds);
            Map<String, Object> dataMap;
            dataMap = new HashMap<String, Object>();
            dataMap.put("recordsTotal", pageBean.getiTotalRecords());
            dataMap.put("recordsFiltered", pageBean.getiTotalRecords());
            dataMap.put("aaData", pageBean.getResults());
            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/html;charset=UTF-8");
            PrintWriter out = null;
            try {
                out = response.getWriter();
                out.write(JSON.toJSONString(dataMap));
            } catch (IOException e) {
                logger.error("查询出错", e);
                e.printStackTrace();
            } finally {
                if (out != null) {
                    out.close();
                }
            }
        } catch (ServiceException e) {
            e.printStackTrace();
        }
    }
    
    /**
     * 
     * <p>Description: 电池注册</p>
     * @param request 请求
     * @param response 响应
     * @return 操作结果
     */
    @RequestMapping(value = "/registerPack.mvc")
    @ResponseBody
    public Map<String, Object> registerPack(HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> map;
        map = new HashMap<String, Object>();
        
        String record;
        record = request.getParameter("record");
        JSONObject jsonOb;
        jsonOb = JSON.parseObject(record);
        
        String sysUser;
        sysUser = String.valueOf(request.getSession().getAttribute("sys.userName"));
        
        TtPack pack;
        TmPackSerial serial;
        Object obId;
        obId = jsonOb.get("pkId");
        
        String id;
        id = obId.toString();
        
        String packCode;
        packCode = jsonOb.getString("packCode");
        List<TmPackSerial> serialNos;
        try {
            serialNos = this.packRegMngService.getSerialNos(packCode);
            pack = this.packRegMngService.findEntityById(id);
            if (serialNos.size() != 0 && pack != null) {
                //电池唯一码数据未变更
                serial = serialNos.get(0);
                //电池唯一码数据更新为“已使用”
                serial.setStatus(STATUS_ONE);
                serial.setUpdateDate(new Date());
                serial.setUpdateUser(sysUser);
                this.packSerialService.updateRecord(serial);
                
                pack.setPackCode(packCode);
                pack.setSimPhoneno(String.valueOf(jsonOb.get("simPhoneno")));
                pack.setCustomId(String.valueOf(jsonOb.get("customId")));
                pack.setPackModel(String.valueOf(jsonOb.get("packModel")));
                //已注册
                pack.setPackregFalg(STATUS_ONE);
                //正常
                pack.setPackStatus(STATUS_ZERO);
                //正常
                pack.setEnableFalg(STATUS_ONE);
                pack.setUpdateUser(sysUser);
                pack.setUpdateDate(new Date());
                map.put("msg", this.packRegMngService.updateRecord(pack));
            } else {
                //电池唯一码或电池数据过期
                map.put("msg", "expire");
                return map;
            }
        } catch (ServiceException e) {
            e.printStackTrace();
            map.put("msg", "error");
        }
        return map;
    }
    
    /**
     * 
     * <p>Description: 更换终端</p>
     * @param request 请求对象
     * @param pack 电池pack
     * @return 操作标志
     */
    @RequestMapping(value = "/changeClient.mvc")
    @ResponseBody
    public Map<String, Object> changePackClinet(HttpServletRequest request, TtPack pack) {
        Map<String, Object> map;
        map = new HashMap<String, Object>();
        
        String sysUser;
        sysUser = (String) request.getSession().getAttribute("sys.userName");
        TtPack packOld;
        TtPack packNew;
        List<TmPackSerial> serialNos;
        try {
            serialNos = this.packRegMngService.findSerialByPackcode(pack.getPackCode());
            packOld = this.packRegMngService.findRegPackByCode(pack.getPackCode());
            packNew = this.packRegMngService.findEntityById(pack.getPkId());
            if (packOld != null && packNew != null && serialNos.size() == 1) {
                packNew.setCustomId(pack.getCustomId());
                packNew.setPackCode(pack.getPackCode());
                packNew.setSimPhoneno(pack.getSimPhoneno());
                packNew.setPackModel(pack.getPackModel());
                packNew.setPackregFalg(STATUS_ONE);
                packNew.setUpdateDate(new Date());
                packNew.setUpdateUser(sysUser);
                //注册电池
                this.packRegMngService.updateRecord(packNew);
            } else {
                map.put("msg", "error");
            }
        } catch (ServiceException e) {
            e.printStackTrace();
        }
        return map;
    }
    
    /**
     * 
     * <p>Description: 获取电池采集终端详情</p>
     * @param request 请求
     * @param response 响应
     * @return 详情信息
     */
    @RequestMapping(value = "/getRegPackDetail.mvc")
    @ResponseBody
    public Map<String, Object> getRegPackDetail(HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> map;
        map = new HashMap<String, Object>();
        //采集终端标识码
        String colClientId;
        colClientId = request.getParameter("colClientId");
        String packCode;
        packCode = request.getParameter("packCode");
        map.put("colClientId", colClientId);
        map.put("packCode", packCode);
        Map<String, Object> detailMap;
        detailMap = new HashMap<String, Object>();
        try {
            detailMap = this.packRegMngService.getPackRegDetail(map);
        } catch (ServiceException e) {
            e.printStackTrace();
        }
        return detailMap;
    }
    
    /**
     * 
     * <p>Description: 查询未注册的电池唯一码</p>
     * @param request 请求
     * @param response 响应
     * @return 查询结果
     */
    @RequestMapping(value = "/getSerialNoList.mvc")
    @ResponseBody
    public Map<String, Object> getSerialNoList(HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> map;
        map = new HashMap<String, Object>();
        try {
            map.put("data", this.packRegMngService.getSerialNos(null));
        } catch (ServiceException e) {
            e.printStackTrace();
        }
        return map;
    }
    /**
     * 
     * <p>Description: 查询客户列表</p>
     * @param request 请求
     * @param response 响应
     * @return 客户列表
     */
    @SuppressWarnings("rawtypes")
    @RequestMapping(value = "/getRegCustoms.mvc")
    @ResponseBody
    public EntityPageBean getRegCustoms(HttpServletRequest request, HttpServletResponse response) {
        JSONArray array;
        array = JSON.parseArray(request.getParameter("aoData"));
        PageBounds pageBounds;
        pageBounds = new PageBounds();
        Map<String, Object> map;
        map = new HashMap<String, Object>();
        if (array != null) {
            Iterator it;
            it = array.iterator();
            while (it.hasNext()) {
                JSONObject obj;
                obj = (JSONObject) it.next();
                if (obj.get("value") != null && !"".equals(obj.get("value") + "")) {
                    map.put(obj.get("name") + "", obj.get("value"));
                }
            }
        }
        pageBounds.setLimit(Integer.parseInt(map.get("iDisplayLength").toString()));
        pageBounds.setPage(Integer.parseInt(map.get("iDisplayStart").toString()) / pageBounds.getLimit() + 1);
        try {
            return this.packRegMngService.findRegCustom(map, pageBounds);
        } catch (ServiceException e) {
            logger.error(e.getMessage(), e);
            return new EntityPageBean<Object>();
        }
    }
    
    /**
     * 
     * <p>Description: 变更电池终端时根据输入的电池Id查询原关联的终端客户信息和SIM卡号码</p>
     * @param request 请求
     * @param response 响应
     * @return 客户
     */
    @RequestMapping(value = "/getRegCustomByPackcode.mvc")
    @ResponseBody
    public Map<String, Object> getRegCustomByPackcode(HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> map;
        map = new HashMap<String, Object>();
        String packCode;
        packCode = request.getParameter("packCode");
        
        try {
            map = this.packRegMngService.getRegInfoByPackcode(packCode);
        } catch (ServiceException e) {
            e.printStackTrace();
        }
        return map;
    }
}
